<template>
  <px-dialog v-model="visible" title="添加考生" width="650" @close="cancel">
    <div v-loading="selectLoading" class="choose-form">
      <px-form ref="formRef" :model="formValue" :rules="formRules" :validate-on-rule-change="false" label-position="right" label-width="120px">
        <px-form-item label="考试计划时间" prop="time">
          <px-date-picker
            v-model="formValue.time"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
          />
        </px-form-item>
        <px-form-item label="选择方式" prop="chooseType">
          <px-select v-model="formValue.chooseType" style="width: 500px" placeholder="请选择" clearable @change="changeSelectType">
            <px-option v-for="item in chooseTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="formValue.chooseType === 'person'" label="选择考生" prop="selected">
          <px-select
            v-model="formValue.selected"
            multiple
            placeholder="请选择"
            filterable
            all-option
            clearable
            collapse-tags
            :max-collapse-tags="3"
            style="width: 500px"
          >
            <px-option v-for="item in optionList" :key="item.value" :label="item.label" :value="item" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="formValue.chooseType === 'role'" label="选择角色" prop="selected">
          <px-select v-model="formValue.selected" placeholder="请选择" filterable clearable style="width: 500px">
            <px-option v-for="item in optionList" :key="item.value" :label="item.label" :value="item" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="formValue.chooseType === 'org'" label="选择组织" prop="selected">
          <px-tree-select
            v-model="formValue.selected"
            :data="optionList"
            :props="{ value: 'deptId', label: 'deptName' }"
            multiple
            :render-after-expand="false"
            show-checkbox
            check-strictly
            check-on-click-node
            filterable
            clearable
            collapse-tags
            :max-collapse-tags="3"
            style="width: 500px"
          />
        </px-form-item>
      </px-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="confirm">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, computed } from "vue";
import { getPersonListAPI, getRoleListAPI, getOrganizationListAPI } from "@/api/knowledge/documentManage";
import { getRoleUserAPI, getPeopleByDeptAPI } from "@/api/knowledge/train";
import dayjs from "dayjs";

const emits = defineEmits(["update:visible", "add"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref();
const formRules = computed(() => ({
  time: [{ required: true, message: "考试计划时间不能为空", trigger: "blur" }],
  chooseType: [{ required: true, message: "选择方式不能为空", trigger: "change" }],
  selected: [{ required: true, message: "选择内容不能为空", trigger: "blur" }]
}));

const disabledDate = time => {
  // 禁用早于今天的日期（不含今天）
  return dayjs(time).isBefore(dayjs(), "day");
};

const state = reactive({
  selectLoading: false,
  formValue: {
    chooseType: "",
    selected: []
  },
  chooseTypeList: [
    {
      name: "人员",
      value: "person"
    },
    {
      name: "角色",
      value: "role"
    },
    {
      name: "组织",
      value: "org"
    }
  ],
  optionList: []
});
const { selectLoading, formValue, chooseTypeList, optionList } = toRefs(state);

const getSelectList = async type => {
  try {
    state.selectLoading = true;
    if (type === "person") {
      // 人员
      state.optionList = await getPersonListAPI();
      state.optionList.forEach(item => {
        item.id = item.userId;
        item.label = `${item.username}-${item.realName}`;
        item.value = item.userId;
      });
    } else if (type === "role") {
      // 角色
      state.optionList = await getRoleListAPI();
      state.optionList.forEach(item => {
        item.id = item.roleId;
        item.label = item.roleName;
        item.value = item.roleId;
      });
    } else if (type === "org") {
      // 组织
      state.optionList = await getOrganizationListAPI();
      renameLabel(state.optionList);
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.selectLoading = false;
  }
};

const renameLabel = data => {
  data.forEach(item => {
    item.label = item.deptName;
    item.value = item.deptId;
    if (item.children) {
      renameLabel(item.children);
    }
  });
};

const changeSelectType = v => {
  state.optionList = [];
  state.formValue.selected = [];
  getSelectList(v);
};

const cancel = () => {
  emits("update:visible", false);
};

const confirm = () => {
  formRef.value.validate(async validate => {
    if (validate) {
      let obj = {};
      let data = [];
      if (state.formValue.chooseType === "role") {
        try {
          state.selectLoading = true;
          const params = {
            pageSize: 9999,
            page: 1,
            sortBy: "desc",
            sortName: "id",
            sysCode: "sys-ifp",
            roleId: state.formValue.selected.value,
            usernameLike: "",
            realNameLike: "",
            phoneLike: "",
            status: -1,
            deptId: null
          };
          data = await getRoleUserAPI(params);
        } catch (err) {
          console.log(err);
        } finally {
          state.selectLoading = false;
        }
      } else if (state.formValue.chooseType === "person") {
        data = state.formValue.selected;
      } else if (state.formValue.chooseType === "org") {
        try {
          state.selectLoading = true;
          const params = {
            page: 1,
            pageSize: 9999,
            deptIdList: state.formValue.selected
          };
          let res = await getPeopleByDeptAPI(params);
          data = res.data;
        } catch (err) {
          console.log(err);
        } finally {
          state.selectLoading = false;
        }
      }
      obj.data = data;
      let time = state.formValue.time;
      let endTime = time[1] ?? "";
      obj.time = [time[0] ?? "", endTime?.split(" ")[0] + " 23:59:59"];
      emits("add", obj);
    }
  });
};

defineExpose({
  cancel
});
</script>
